package com.youdoneed.community.forum.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.github.pagehelper.PageHelper;
import com.youdoneed.community.common.vo.PageData;
import com.youdoneed.community.forum.entity.Forumnotice;
import com.youdoneed.community.forum.vo.ForumlikespointrecordVo;
import com.youdoneed.friends.feign.FriendsClient;
import com.youdoneed.friends.vo.UserRelationsVO;
import com.youdoneed.news.feign.NewsClient;
import com.youdoneed.news.model.CmfPostsDtlVo;
import com.youdoneed.user.feign.UserFeignClient;
import com.youdoneed.user.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.youdoneed.base.application.AppException;
import com.youdoneed.community.common.utils.StringUUIdUtil;
import com.youdoneed.community.forum.dao.ForumcommentMapper;
import com.youdoneed.community.forum.dao.ForumlikespointrecordMapper;
import com.youdoneed.community.forum.dao.ForummessageMapper;
import com.youdoneed.community.forum.entity.Forumcomment;
import com.youdoneed.community.forum.entity.Forumlikespointrecord;
import com.youdoneed.community.forum.entity.Forummessage;

import com.youdoneed.community.forum.service.ForumServciceStatic;

@Service
public class ForumlikespointrecordService {
    private final Logger logger = LoggerFactory.getLogger(ForumlikespointrecordService.class);

    @Autowired
    ForumlikespointrecordMapper forumlikespointrecordMapper;

    @Autowired
    ForummessageMapper forummessageMapper;

    @Autowired
    ForumcommentMapper forumcommentMapper;

    @Autowired
    ForummessageService forummessageService;

    @Autowired
    NewsClient newsClient;

    @Autowired
    UserFeignClient userFeignClient;

    @Autowired
    ForumNoticeService forumNoticeService;

    @Autowired
    FriendsClient friendsClient;

    /**
     * 保存点赞记录接口
     *
     * @param forumlikespointrecord
     * @return 1：帖子已删除!
     * 2：已点赞！
     * 3：点赞成功！
     * 4：评论已删除!
     * 0：点赞失败！
     * @author lid
     * @date 2017.6.6
     */
    @Transactional
    public Integer saveForumlikespointrecord(Forumlikespointrecord forumlikespointrecord) {
        logger.info("ForumlikespointrecordService:saveForumlikespointrecord");
        try {

            //帖子的点赞数+1
            if (ForumServciceStatic.LIKES_TYPE_MESSAGE.equals(forumlikespointrecord.getLikesType())) {
                logger.info("给帖子点赞！forumMsgId:" + forumlikespointrecord.getForumMsgId());

                //0表示给帖子点赞
                Forummessage forummessage = forummessageMapper.selectByPrimaryKey(forumlikespointrecord.getForumMsgId());

                if (null == forummessage) {
                    logger.info("被点赞的帖子已删除!");
                    return 1;
                }

                //判断当前用户是否已经点赞，同一篇帖子不可重复点赞
                if (StringUtils.hasText(forumlikespointrecord.getForumMsgId())) {
                    int count = forumlikespointrecordMapper.countByUserIdAndForumMsgId(
                            forumlikespointrecord.getUserId(), forumlikespointrecord.getForumMsgId());
                    logger.info("count：" + count);
                    if (0 < count) {
                        logger.info("当前用户已经对当前帖子点赞！");
                        return 2;
                    }
                }
                forumlikespointrecord.setLikesPointRecordId(StringUUIdUtil.getUUID());
                forumlikespointrecord.setCreateDate(new Date());
                forumlikespointrecordMapper.insert(forumlikespointrecord);

                /**
                 * 添加通知
                 */
                Forumnotice notice = new Forumnotice();
                notice.setCreateDate(new Date());
                notice.setForumNoticeId(StringUUIdUtil.getUUID());
                notice.setNoticeUserNickname(forumlikespointrecord.getUserNickName());
                notice.setNoticeUserHeadUrl(forumlikespointrecord.getUserHeadUrl());
                notice.setNoticeUserId(forumlikespointrecord.getUserId());
                notice.setReadStatus(0);

                /**
                 * 自己点赞自己的帖不生成通知
                 */
                if (forummessage.getUserId().equals(forumlikespointrecord.getUserId())) {
                    logger.info("给自己的帖子点赞，不生成通知！");
                    notice = null;
                } else if (StringUtils.hasText(forummessage.getMsgSourceType()) &&
                        ForumServciceStatic.likePointMsg.equals(forummessage.getMsgSourceType())) {
                    logger.info("给点赞帖子点赞，不生成通知！");
                    notice = null;
                } else {
                    notice.setUserId(forummessage.getUserId());
                    notice.setNoticeType(ForumServciceStatic.msgLikePointNotice);
                    notice.setSourceId(forummessage.getForumMsgId());
                    notice.setSourceDesc("赞了你的帖子！");
                    notice.setSourceType(forummessage.getMsgType());
                    forumNoticeService.insertSelective(notice);
                    logger.info("保存通知消息成功！id:" + notice.getForumNoticeId());
                }

                /**
                 * 点赞生成新的帖子
                 * 1，只有帖子msg并且msgSourceType为空才可以生成点赞帖
                 * 2，点赞自己的贴不能生成点赞帖
                 * 3，帖子删除，所有点赞贴删除
                 * 4，取消点赞，点赞贴删除
                 */
                /*if((ForumServciceStatic.msg.equals(forummessage.getMsgType()))
                        &&(!forummessage.getUserId().equals(forumlikespointrecord.getUserId()))
						&&(!StringUtils.hasText(forummessage.getMsgSourceType()))){
					logger.info("当前贴为非点赞贴");
					*//**
                 * 判断是否已经生成过点赞贴，如果已经生成，则将删除状态改为未删除
                 *//*
					Forummessage likePointMsg = forummessageMapper.getLikePointMsgByUserIdAndSourceId(forumlikespointrecord.getUserId(),
							forumlikespointrecord.getForumMsgId());

					if(null != likePointMsg){
						logger.info("当前点赞贴已存在，改变其删除状态");
						forummessageMapper.updateLikePointMsgStatus(forumlikespointrecord.getForumMsgId(), 0);
					}else{
						logger.info("生成点赞贴!");

						User user = userFeignClient.getUser(forumlikespointrecord.getUserId()).getData();
						if(null != user) {
							Forummessage msg = new Forummessage();
							msg.setHasPraised(0);
							*//**
                 * 点赞生成的帖子的公开状态是朋友可见
                 *//*
							msg.setAllowViewStatus(ForumServciceStatic.openToFriends);
							msg.setCommentCount(0);
							msg.setCreateDate(new Date());
							msg.setFirstImageScale(null);
							msg.setForumMsgId(StringUUIdUtil.getUUID());
							msg.setHeat(0);
							msg.setImageLayoutType(0);
							msg.setLikesCount(0);
							msg.setMsgContent(null);
							msg.setMsgDelete(0);
							msg.setMsgStruct(null);
							msg.setMsgType(forummessage.getMsgType());
							msg.setMsgSourceType(ForumServciceStatic.likePointMsg);
							msg.setNickName(user.getName());
							msg.setPostionLabel(null);
							msg.setProhibit(0);
							msg.setReportCount(0);
							msg.setShareCount(0);
							msg.setUserHeadUrl(forumlikespointrecord.getUserHeadUrl());
							msg.setUserId(forumlikespointrecord.getUserId());
							msg.setSourceId(forummessage.getForumMsgId());
							forummessageMapper.insert(msg);
							logger.info("保存点赞贴成功！");
						}
					}
				}*/

                if ((null != forummessage) && (null == forummessage.getLikesCount())) {
                    forummessageMapper.updateLikesCount(forummessage.getForumMsgId(), 1);
                    return 3;
                }

                if ((null != forummessage) && (null != forummessage.getLikesCount())) {
                    forummessageMapper.updateLikesCount(forummessage.getForumMsgId(), forummessage.getLikesCount() + 1);
                    return 3;
                }
            }

            if (ForumServciceStatic.LIKES_TYPE_COMMENT.equals(forumlikespointrecord.getLikesType())) {
                //1表示给评论点赞
                logger.info("给评论点赞！forumMsgId:" + forumlikespointrecord.getForumMsgId());

                Forumcomment forumcomment = forumcommentMapper.selectByPrimaryKey(forumlikespointrecord.getForumMsgId());
                /**
                 * 给评论点赞，那么sourceId还是需要给帖子的id
                 */
                CmfPostsDtlVo cmfPostsDtlVo = new CmfPostsDtlVo();

                if (null == forumcomment) {
                    logger.info("被点赞的评论为空");

                    return 4;
                }

                //判断当前用户是否已经点赞，同一篇帖子不可重复点赞
                if (StringUtils.hasText(forumlikespointrecord.getForumMsgId())) {
                    int count = forumlikespointrecordMapper.countByUserIdAndForumMsgId(
                            forumlikespointrecord.getUserId(), forumlikespointrecord.getForumMsgId());
                    logger.info("count：" + count);
                    if (0 < count) {
                        logger.info("当前用户已经对当前帖子点赞！");
                        return 2;
                    }
                }
                forumlikespointrecord.setLikesPointRecordId(StringUUIdUtil.getUUID());
                forumlikespointrecord.setCreateDate(new Date());
                forumlikespointrecordMapper.insert(forumlikespointrecord);

                /**
                 * 添加通知
                 */
                Forumnotice notice = new Forumnotice();
                notice.setCreateDate(new Date());
                notice.setForumNoticeId(StringUUIdUtil.getUUID());
                notice.setNoticeUserNickname(forumlikespointrecord.getUserNickName());
                notice.setNoticeUserHeadUrl(forumlikespointrecord.getUserHeadUrl());
                notice.setNoticeUserId(forumlikespointrecord.getUserId());
                notice.setReadStatus(0);

                if (!StringUtils.hasText(forumcomment.getForumMsgId())) {
                    logger.info("被点赞的评论的msgId为空！");
                    return 1;
                }
                Forummessage forummessage = forummessageMapper.selectByPrimaryKey(forumcomment.getForumMsgId());

                if (null == forummessage) {
                    logger.info("forumcomment.getForumMsgId():" + forumcomment.getForumMsgId());
                    cmfPostsDtlVo = newsClient.getPostsDtlById(Long.valueOf(forumcomment.getForumMsgId())).getData();
                    if (null == cmfPostsDtlVo) {
                        logger.info("被点赞的评论的帖子或者新闻为空！");
                        return 1;
                    }
                }
                logger.info("null != forummessage");

                if (StringUtils.hasText(forumcomment.getUserId())) {
                    if (forumcomment.getUserId().equals(forumlikespointrecord.getUserId())) {
                        logger.info("给自己的评论点赞，不生成通知!");
                        notice = null;
                    } else {
                        notice.setUserId(forumcomment.getUserId());
                        if (null != forummessage) {
                            notice.setNoticeType(ForumServciceStatic.cmtLikePointNotice);
                            notice.setSourceId(forummessage.getForumMsgId());
                            notice.setSourceDesc("给你的评论点赞");
                            notice.setSourceType(forummessage.getMsgType());
                            forumNoticeService.insertSelective(notice);
                            logger.info("保存通知消息成功！id:" + notice.getForumNoticeId());

                        } else if (null != cmfPostsDtlVo) {

                            notice.setNoticeType(ForumServciceStatic.newsCmtLikePointNotice);
                            notice.setSourceId(cmfPostsDtlVo.getId().toString());
                            notice.setSourceDesc("赞了你的评论！");
                            notice.setSourceType(cmfPostsDtlVo.getTpl());
                            forumNoticeService.insertSelective(notice);
                            logger.info("保存通知消息成功！id:" + notice.getForumNoticeId());
                        }
                    }
                }
                logger.info("userId is null");

                if ((null != forumcomment) && (null == forumcomment.getLikesCount())) {
                    forumcommentMapper.updateLikesCount(forumcomment.getForumCommentId(), 1);
                    logger.info("null == forumcomment.getLikesCount()");
                    return 3;
                }

                if ((null != forumcomment) && (null != forumcomment.getLikesCount())) {
                    forumcommentMapper.updateLikesCount(forumcomment.getForumCommentId(), forumcomment.getLikesCount() + 1);
                    logger.info("null != forumcomment.getLikesCount()");
                    return 3;
                }
            }

            if (ForumServciceStatic.LIKES_TYPE_NEWS.equals(forumlikespointrecord.getLikesType())) {

                //判断当前用户是否已经点赞，同一篇帖子不可重复点赞
                if (StringUtils.hasText(forumlikespointrecord.getForumMsgId())) {
                    int count = forumlikespointrecordMapper.countByUserIdAndForumMsgId(
                            forumlikespointrecord.getUserId(), forumlikespointrecord.getForumMsgId());
                    logger.info("count：" + count);
                    if (0 < count) {
                        logger.info("当前用户已经对当前帖子点赞！");
                        return 2;
                    }
                }
                forumlikespointrecord.setLikesPointRecordId(StringUUIdUtil.getUUID());
                forumlikespointrecord.setCreateDate(new Date());
                forumlikespointrecordMapper.insert(forumlikespointrecord);

                //2表示给新闻点赞
                logger.info("给新闻点赞！forumMsgId:" + forumlikespointrecord.getForumMsgId());
                //新闻的点赞数+1
                newsClient.updatePostLikes(Long.valueOf(forumlikespointrecord.getForumMsgId()), "0");
            }
            return 3;
        } catch (Exception e) {
            logger.error("保存点赞记录异常：" + e);
            return 0;
        }
    }

    @Transactional
    public int cancelLikesPoint(String userId, String sourceId, String likesType) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("userId参数为空！");
        }

        if (!StringUtils.hasText(sourceId)) {
            throw new AppException("sourceId参数为空！");
        }

        logger.info("cancelLikesPoint!userId:" + userId + ",sourceId=" + sourceId + ",likesType=" + likesType);

        //判断是否存在点赞数据
        int count = forumlikespointrecordMapper.countByUserIdAndForumMsgId(userId, sourceId);
        logger.info("count:" + count);

        if (0 == count) {
            logger.info("未找到当前的点赞信息!已取消点赞！");
            return 1;
        }

        try {
            int result = forumlikespointrecordMapper.cancelLikesPoint(userId, sourceId);

            logger.info("result:" + result);
            //帖子或者评论的点赞数-1
            if (ForumServciceStatic.LIKES_TYPE_MESSAGE.equals(likesType)) {
                /**
                 * 取消点赞  所有点赞帖删除
                 */
                //forummessageMapper.deleteLikePointMsgs(sourceId);

                logger.info("取消给帖子的点赞！");
                //当前为给帖子点赞
                Forummessage forummessage = forummessageMapper.selectByPrimaryKey(sourceId);
                if (null == forummessage) {
                    throw new AppException("未找到当前被取消点赞的帖子！sourceId：" + sourceId);
                }
                logger.info("原点赞数：" + forummessage.getLikesCount());
                forummessageMapper.updateLikesCount(sourceId, forummessage.getLikesCount() - 1);
                //删除通知
                forumNoticeService.deleteBySourceId(sourceId);
                return result;
            }

            if (ForumServciceStatic.LIKES_TYPE_COMMENT.equals(likesType)) {
                logger.info("取消给评论的点赞！");
                Forumcomment forumcomment = forumcommentMapper.selectByPrimaryKey(sourceId);
                if (null == forumcomment) {
                    throw new AppException("未找到当前被取消点赞的评论！sourceId：" + sourceId);
                }

                if ((null != forumcomment.getCommentCount())
                        && (0 < forumcomment.getCommentCount())) {
                    forumcommentMapper.updateLikesCount(sourceId, forumcomment.getCommentCount() - 1);
                } else {
                    forumcommentMapper.updateLikesCount(sourceId, 0);
                }
                //删除通知
                forumNoticeService.deleteBySourceId(sourceId);
                return result;
            }

            return result;
        } catch (Exception e) {
            logger.error("保存点赞记录异常：" + e);
            return 0;
        }
    }

    /**
     * 根据帖子id获取点赞信息
     *
     * @param forumMsgId
     * @return List<Forumlikespointrecord>
     * @author lid
     * @date 2017.6.22
     */
    @Transactional
    public List<Forumlikespointrecord> getLikesRecordByMsgId(String forumMsgId) {
        if (!StringUtils.hasText(forumMsgId)) {
            logger.info("forumMsgId参数为空！");
            throw new AppException("forumMsgId参数为空！");
        }
        logger.info("getLikesRecordByMsgId!forumMsgId:" + forumMsgId);
        try {
            List<Forumlikespointrecord> listForumlikespointrecord =
                    forumlikespointrecordMapper.getLikesRecordByMsgId(forumMsgId);

            logger.info("listForumlikespointrecord.size():" + listForumlikespointrecord.size());

            return listForumlikespointrecord;
        } catch (Exception e) {
            logger.error("获取点赞记录异常：" + e);
            return null;
        }
    }

    /**
     * 首页根据帖子id分页获取点赞信息，并判断好友关系
     *
     * @param forumMsgId
     * @return List<Forumlikespointrecord>
     * @author lid
     * @date 2017.6.22
     */
    @Transactional
    public PageData getLikesRecordByMsgId(String userId, String forumMsgId, Integer currentPage, Integer rows) {

        if (null == rows) {
            throw new AppException("rows is null");
        }

        if (null == currentPage) {
            throw new AppException("currentPage is null");
        }

        if (!StringUtils.hasText(userId)) {
            throw new AppException("userId参数为空！");
        }

        if (!StringUtils.hasText(forumMsgId)) {
            throw new AppException("msgId参数为空！");
        }

        PageData page = new PageData();

        try {
            List<Forumlikespointrecord> listLikesRecord = forumlikespointrecordMapper.getLikesRecordByMsgId(forumMsgId);
            if (null == listLikesRecord
                    || 0 == listLikesRecord.size()) {
                List<ForumlikespointrecordVo> listForumlikespointrecordVo = new ArrayList<ForumlikespointrecordVo>();
                page.setTotal(0);
                page.setRows(listForumlikespointrecordVo);
                return page;
            }

            Integer length = listLikesRecord.size();
            page.setTotal(length);

            Integer startIndex = rows * currentPage;
            Integer endIndex = rows * (currentPage + 1);
            if (startIndex > length) {
                List<ForumlikespointrecordVo> listForumlikespointrecordVo = new ArrayList<ForumlikespointrecordVo>();
                page.setRows(listForumlikespointrecordVo);
                return page;
            }

            List<ForumlikespointrecordVo> listVo = new ArrayList<>(listLikesRecord.size());
            UserRelationsVO userRelationsVO = friendsClient.findFriendIds(4).getData();

            if (endIndex < length) {
                List<Forumlikespointrecord> listForumlikespointrecord = listLikesRecord.subList(startIndex, endIndex);

                for (int i = 0; i < listForumlikespointrecord.size(); i++) {
                    Forumlikespointrecord likesRecord = listForumlikespointrecord.get(i);
                    ForumlikespointrecordVo vo = new ForumlikespointrecordVo();
                    vo.setForumlikespointrecord(likesRecord);
                    if (userRelationsVO.getFriendIds().contains(likesRecord.getUserId())) {
                        vo.setFriendHandle(1);
                    } else if (userRelationsVO.getHasConfirmUserIds().contains(likesRecord.getUserId())) {
                        vo.setFriendHandle(3);
                    } else {
                        vo.setFriendHandle(2);
                    }
                    listVo.add(vo);
                }

                page.setRows(listVo);
                return page;
            }

            List<Forumlikespointrecord> listResult = listLikesRecord.subList(startIndex, length);

            for (int i = 0; i < listResult.size(); i++) {
                Forumlikespointrecord likesRecord = listResult.get(i);
                ForumlikespointrecordVo vo = new ForumlikespointrecordVo();
                vo.setForumlikespointrecord(likesRecord);
                if (userRelationsVO.getFriendIds().contains(likesRecord.getUserId())) {
                    vo.setFriendHandle(1);
                } else if (userRelationsVO.getHasConfirmUserIds().contains(likesRecord.getUserId())) {
                    vo.setFriendHandle(3);
                } else {
                    vo.setFriendHandle(2);
                }
                listVo.add(vo);
            }

            page.setRows(listVo);
            return page;
        } catch (Exception e) {
            throw new AppException("获取点赞记录失败!");
        }
    }

    /**
     * 获取用户对新闻帖子的点赞记录
     *
     * @return
     */
    @Transactional
    public Integer hasPraised(String userId, String sourceId) {
        if (!StringUtils.hasText(userId)) {
            logger.info("userId参数为空！");
            throw new AppException("userId参数为空！");
        }

        if (!StringUtils.hasText(sourceId)) {
            logger.info("sourceId参数为空！");
            throw new AppException("sourceId参数为空！");
        }
        Integer count = forumlikespointrecordMapper.countByUserIdAndForumMsgId(userId, sourceId);
        return count;
    }

    /**
     * 根据用户获取所有点赞记录的msgId
     *
     * @param userId
     * @return List<String>
     * @author lid
     * @date 2017.10.11
     */
    @Transactional
    public List<String> getLikePointMsgsByUserId(String userId) {
        if (!StringUtils.hasText(userId)) {
            logger.info("userId参数为空！");
            throw new AppException("userId参数为空！");
        }
        try {
            return forumlikespointrecordMapper.getLikePointMsgsByUserId(userId);
        } catch (Exception e) {
            throw new AppException("获取点赞记录失败!");
        }
    }

    @Transactional
    public int deleleLikesPointRecordByMsgId(String msgId) {
        if (!StringUtils.hasText(msgId)) {
            logger.info("msgId参数为空！");
            throw new AppException("msgId参数为空！");
        }

        try {
            return forumlikespointrecordMapper.deleleLikesPointRecordByMsgId(msgId);
        } catch (Exception e) {
            throw new AppException("删除点赞记录失败!");
        }
    }
}
